package com.wbao.dianniu.im;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.wbao.dianniu.adapter.FollowAdapter;
import com.wbao.dianniu.data.HeadData;
import com.wbao.dianniu.indexView.CharacterParser;
import com.wbao.dianniu.indexView.PinyinComparator;
import com.wbao.dianniu.indexView.SideBar;
import com.wbao.dianniu.indexView.SortModel;
import com.wbao.dianniu.indexView.SideBar.OnTouchingLetterChangedListener;
import com.wbao.dianniu.listener.IFollowListListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.FollowListManager;
import com.wbao.dianniu.ui.BaseActivity;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 我的关注
 *
 * @author yejianjun
 */
public class FollowListActivity extends BaseActivity implements OnClickListener, OnItemClickListener, OnTouchingLetterChangedListener, IFollowListListener {
    private SideBar sideBar;
    private TextView dialog;
    private FollowAdapter adapter;
    private ListView sortListView;
//	private ClearEditText mClearEditText;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> dataList;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private FollowListManager manager;
    private int friendId = 0;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_follow_list);
        title = getIntent().getStringExtra(Const.INTENT_TITLE);
        if (TextUtils.isEmpty(title)) {
            title = getResources().getString(R.string.my_follow_text);
        }
        setTitleName(title);
        initView();
        friendId = getIntent().getIntExtra(Const.INTENT_ID, GlobalContext.getAccountId());
        manager = new FollowListManager(this);
        manager.addFollowListListener(this);
        manager.followList(friendId, 0, 999);
    }

    private void initView() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        dataList = new ArrayList<SortModel>();
//		dataList = filledData(getResources().getStringArray(R.array.date));
        adapter = new FollowAdapter(this, dataList);
        // 根据a-z进行排序源数据
        Collections.sort(dataList, pinyinComparator);

        sideBar = (SideBar) findViewById(R.id.follow_sidebar);
        dialog = (TextView) findViewById(R.id.follow_list_dialog);
        sortListView = (ListView) findViewById(R.id.follow_list_content);
        sideBar.setTextView(dialog);
        sideBar.setOnTouchingLetterChangedListener(this);
        sortListView.setOnItemClickListener(this);
        sortListView.setAdapter(adapter);

//		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);
//		mClearEditText.addTextChangedListener(watcher);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        //这里要利用adapter.getItem(position)来获取当前position所对应的对象
        Integer accountId = ((SortModel) adapter.getItem(position)).getFriendId();
        Utils.intoHeadInfoActivity(accountId, FollowListActivity.this);
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        //该字母首次出现的位置
        int position = adapter.getPositionForSection(s.charAt(0));
        if (position != -1) {
            sortListView.setSelection(position);
        }
    }

    TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
            filterData(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<SortModel> filledData(HeadData[] date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < date.length; i++) {
            SortModel sortModel = new SortModel();
            sortModel.setFriendId(date[i].followId);
            sortModel.setName(date[i].realName);
            sortModel.setSex(date[i].sex);
            sortModel.setIndustryAuthority(date[i].isIndustryAuthority);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i].realName);
            String sortString = pinyin.substring(0, 1).toUpperCase(Locale.getDefault());
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase(Locale.getDefault()));
            } else {
                sortModel.setSortLetters("#");
            }
            sortModel.setLabel(date[i].label);
            sortModel.setUrl(date[i].headPic);
            mSortList.add(sortModel);
        }
        return mSortList;
    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = dataList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : dataList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    @Override
    public void onFollowListFailure(int errorCode, String errorMsg) {
    }

    @Override
    public void onFollowListSuccess(List<HeadData> list) {
        if (null == list)
            return;
        HeadData[] heads = new HeadData[list.size()];
        for (int i = 0; i < heads.length; i++) {
            heads[i] = new HeadData();
            heads[i].followId = list.get(i).followId;
            heads[i].headPic = list.get(i).headPic;
            heads[i].label = list.get(i).label;
            heads[i].realName = list.get(i).realName;
            heads[i].sex = list.get(i).sex;
            heads[i].isIndustryAuthority = list.get(i).isIndustryAuthority;
        }
        dataList = filledData(heads);
        adapter.updateListView(dataList);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeFollowListListener(this);
        }
    }
}
